package com.example.opengldemo.mbo;

import android.opengl.GLSurfaceView;
import android.opengl.GLES30;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import com.example.opengldemo.R;
import com.example.opengldemo.util.MatrixState;
import com.example.opengldemo.util.TextureUtil;

import android.content.Context;

class MySurfaceView extends GLSurfaceView {
    
	private final float TOUCH_SCALE_FACTOR = 180.0f/320;
	private float mPreviousY;
    private float mPreviousX;
	private SceneRenderer mRenderer;
	BallAndCube mBallAndCube;
    int textureIdBall;

	public MySurfaceView(Context context) {
        super(context);
        this.setEGLContextClientVersion(3);
        mRenderer = new SceneRenderer();
        setRenderer(mRenderer);
        setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    public boolean onTouchEvent(MotionEvent e) {
        float y = e.getY();
        float x = e.getX();
        switch (e.getAction()) {
        case MotionEvent.ACTION_MOVE:
            float dy = y - mPreviousY;
            float dx = x - mPreviousX;
            
            if(mBallAndCube==null){
            	return false;
            }
            mBallAndCube. yAngle += dx * TOUCH_SCALE_FACTOR;
            mBallAndCube.zAngle+= dy * TOUCH_SCALE_FACTOR;
        }
        mPreviousY = y;
        mPreviousX = x;
        return true;
    }

	private class SceneRenderer implements Renderer
    {   		
        public void onDrawFrame(GL10 gl) 
        {
            GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);              
            MatrixState.pushMatrix();
            mBallAndCube.drawSelf(textureIdBall);
            MatrixState.popMatrix();
        }   

        public void onSurfaceChanged(GL10 gl, int width, int height) {

        	GLES30.glViewport(0, 0, width, height); 
            float ratio= (float) width / height;
            MatrixState.setProjectFrustum(-ratio, ratio, -1, 1, 4f, 100);
            MatrixState.setCamera(0,0,8.0f,0f,0f,0f,0f,1.0f,0.0f); 
        }

        public void onSurfaceCreated(GL10 gl, EGLConfig config) {

            GLES30.glClearColor(0.0f,0.0f,0.0f, 1.0f);  

            GLES30.glEnable(GLES30.GL_DEPTH_TEST);

            GLES30.glEnable(GLES30.GL_CULL_FACE);

            MatrixState.setInitStack();

            textureIdBall= TextureUtil.getTextureId(MySurfaceView.this , R.drawable.android_robot0 , null , false);
            mBallAndCube=new BallAndCube(MySurfaceView.this,1.5f);

            UpdateThread  mt=new UpdateThread(MySurfaceView.this);
            mt.start();
        }
    }
}
